const global = getApp().globalData;
const Api = global.Api;
const wxApi = global.wxApi;
const util = global.util;

Page({
  data: {
    goodsData: null,
    paying: false
  },
  onLoad( options ) {
    this.init(options)
  },
  init( options ) {
    let goodsData = util.decodeURI( options.data );
    wxApi.setNavTitle(goodsData.name);
    this.type = options.type;
    this.setData({
      goodsData: goodsData
    })
  },
  onPay() {
    let self = this;
    let type = this.type;
    let goodsData = this.data.goodsData;
    let params = {};
    const types = ['textbookId', 'memoryId', 'paperId'];
    params[ type ] = type;
    params[ types[ type ] ] = goodsData.id;
    if ( this.getPaying() ) {
      return;
    }
    this.setPaying( true );
    Api.createOrders( params, res => {
      console.log( res );
      if (res === null) {
        wxApi.navigateTo( '../buy-result/buy-result', {
          type: 'success'
        })
        return;
      }
      let outTradeNo = res.outTradeNo;
      if (goodsData.preferentialPrice == 0) {
        this.studyBeansBuyFlow(outTradeNo);
      } else {
        this.mpBuyFlow(outTradeNo);
      }
      
    } )
  },
  studyBeansBuyFlow(outTradeNo) {
    Api.createStudyBeansOrder(outTradeNo, (res, code) => {
      if (code == 0) {
        wxApi.navigateTo( '../buy-result/buy-result', {
          type: 'success'
        })
      } else {
        wxApi.navigateTo( '../buy-result/buy-result', {
          type: 'fail'
        })
      }
    })
  },
  mpBuyFlow( outTradeNo ) {
    let self = this;
    wx.login({
      success(res) {
        let code = res.code;
        if ( res.code ) {
          let payParams = {
            outTradeNo: outTradeNo,
            authCode: code
          }
          Api.payOrder( payParams, (res, code) => {
            if ( code != 0 ) {
              self.setPaying( false );
              return;
            }
            let params = res.signMap;
            params.success = function ( res ) {
              self.setPaying( false );
              wxApi.navigateTo( '../buy-result/buy-result', {
                type: 'success'
              })
            }
            params.fail = function ( res ) {
              let errMsg = res.errMsg;
              self.setPaying( false );
              if ( errMsg.indexOf( 'cancel' ) > -1 ) {
                return
              }
              wxApi.navigateTo( '../buy-result/buy-result', {
                type: 'fail'
              })
            }
            wx.requestPayment( params );
          })
        }
      }
    })
  },
  setPaying( val ) {
    this.setData({
      paying: val
    })
  },
  getPaying() {
    return this.data.paying
  }
}) 